<template>
  <div class="receivable-container">
    <!-- 搜索表单 -->
    <div class="search-box">
      <el-input
        v-model="searchForm.FlowingWaterNumber"
        placeholder="请输入流水号"
        clearable
        style="width: 200px"
        @keyup.enter="handleSearch"
      />
      <el-input
        v-model="searchForm.PayableManagementName"
        placeholder="请输入名称"
        clearable
        style="width: 200px"
        @keyup.enter="handleSearch"
      />
      <el-select
        v-model="searchForm.PayableManagementType"
        placeholder="请选择分类"
        clearable
        style="width: 200px"
      >
        <el-option
          v-for="item in categoryOptions"
          :key="item.financialCategoryId"
          :label="item.categoryName"
          :value="item.financialCategoryId"
        />
      </el-select>
      <el-input
        v-model="searchForm.Payer"
        placeholder="请输入付款方"
        clearable
        style="width: 200px"
        @keyup.enter="handleSearch"
      />
      <el-select
        v-model="searchForm.State"
        placeholder="请选择状态"
        clearable
        style="width: 150px"
      >
        <el-option label="未审批" :value="0" />
        <el-option label="审批成功" :value="1" />
        <el-option label="已驳回" :value="2" />
        <el-option label="未收款" :value="5" />
        <el-option label="部分收款" :value="6" />
        <el-option label="已收清" :value="7" />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 240px"
        @change="handleDateChange"
      />
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>重置
      </el-button>
    </div>

    <!-- 操作按钮 -->
    <div class="action-box">
      <el-button 
        v-if="getCurrentRid() !== 2"
        type="primary" 
        @click="handleAdd"
      >
        <el-icon><Plus /></el-icon>新增
      </el-button>
      <el-button type="success" @click="handleExport" :loading="exportLoading">
        <el-icon><Download /></el-icon>导出Excel
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      v-loading="loading"
      height="calc(100vh - 320px)"
      header-cell-class-name="custom-header"
      cell-class-name="custom-cell"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        prop="flowingWaterNumber"
        label="流水号"
        align="center"
      />
      <el-table-column
        prop="receivablesManagementName"
        label="名称"
        align="center"
      />
      <el-table-column label="分类" align="center">
        <template #default="{ row }">
          {{ getCategoryName(row.receivablesManagementType) }}
        </template>
      </el-table-column>
      <el-table-column prop="recipients" label="收款方" align="center" />
      <el-table-column
        prop="amountReceivable"
        label="应收金额"
        align="center"
      />
      <el-table-column prop="paidInAmount" label="实收金额" align="center" />
      <el-table-column prop="remainingAmount" label="剩余金额" align="center" />
      <el-table-column prop="state" label="状态" align="center">
        <template #default="{ row }">
          <el-tag :type="getStateTagType(row.state)" disable-transitions>
            {{ formatState(row.state) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="creatTime" label="创建时间" align="center">
        <template #default="{ row }">
          {{ formatTime(row.creatTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320" align="center" fixed="right">
        <template #default="{ row }">
          <!-- 未审批时：编辑、删除、查看、审批 -->
          <template v-if="row.state === 0">
            <el-button
              v-if="getCurrentRid() !== 2"
              size="small"
              type="primary"
              icon="el-icon-edit"
              @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              v-if="getCurrentRid() !== 2"
              size="small"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(row.receivablesManagementId)"
              >删除</el-button
            >
            <el-button
              size="small"
              type="info"
              icon="el-icon-view"
              @click="handleView(row)"
              >查看</el-button
            >
            <el-button
              v-if="getCurrentRid() === 2"
              size="small"
              type="warning"
              icon="el-icon-document-checked"
              @click="handleApproval(row)"
              >审批</el-button
            >
          </template>

          <!-- 审批成功后：只有查看功能 -->
          <template v-else-if="row.state === 1 || row.state === 6">
            <el-button
              size="small"
              type="info"
              icon="el-icon-view"
              @click="handleView(row)"
              >查看</el-button
            >
            <el-button
              v-if="getCurrentRid() === 2 && canContinuePayment(row)"
              size="small"
              type="success"
              icon="el-icon-check"
              @click="handlePayment(row)"
              >收款</el-button
            >
            <el-button
              v-if="getCurrentRid() === 2 && !canContinuePayment(row)"
              size="small"
              type="warning"
              disabled
              :title="`已达到最大收款次数限制(${MAX_PAYMENT_TIMES}次)`"
              >收款已限制</el-button
            >
          </template>

          <!-- 已收清：只能查看 -->
          <template v-else-if="row.state === 7">
            <el-button
              size="small"
              type="info"
              icon="el-icon-view"
              @click="handleView(row)"
              >查看</el-button
            >
          </template>

          <!-- 已驳回：编辑、删除、查看 -->
          <template v-else-if="row.state === 2">
            <el-button
              v-if="getCurrentRid() !== 2"
              size="small"
              type="primary"
              icon="el-icon-edit"
              @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              v-if="getCurrentRid() !== 2"
              size="small"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(row.receivablesManagementId)"
              >删除</el-button
            >
            <el-button
              size="small"
              type="info"
              icon="el-icon-view"
              @click="handleView(row)"
              >查看</el-button
            >
          </template>

          <!-- 其他状态：查看 -->
          <template v-else>
            <el-button
              size="small"
              type="info"
              icon="el-icon-view"
              @click="handleView(row)"
              >查看</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="searchForm.PageIndex"
        v-model:page-size="searchForm.PageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
      <el-form
        :model="formData"
        label-width="90px"
        :rules="rules"
        ref="formRef"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="流水号" prop="flowingWaterNumber">
              <el-input v-model="formData.flowingWaterNumber" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="receivablesManagementName">
              <el-input v-model="formData.receivablesManagementName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="receivablesManagementType">
              <el-select
                v-model="formData.receivablesManagementType"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.financialCategoryId"
                  :label="item.categoryName"
                  :value="item.financialCategoryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后付款日" prop="lastPaymentDate">
              <el-date-picker
                v-model="formData.lastPaymentDate"
                type="datetime"
                placeholder="选择日期时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款方" prop="payer">
              <el-input v-model="formData.payer" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款方" prop="recipients">
              <el-input v-model="formData.recipients" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应收金额" prop="amountReceivable">
              <el-input-number
                v-model="formData.amountReceivable"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款次数" prop="numberOfPayments">
              <el-input-number
                v-model="formData.numberOfPayments"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialogVisible"
      title="应收审批"
      width="60%"
      :before-close="handleApprovalClose"
      destroy-on-close
    >
      <div class="approval-dialog">
        <!-- 基本信息展示 -->
        <div class="receivable-info">
          <el-descriptions title="收款信息" :column="2" border>
            <el-descriptions-item label="流水号">
              {{ currentApprovalReceivable?.flowingWaterNumber || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="名称">
              {{ currentApprovalReceivable?.receivablesManagementName || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="类别">
              {{ getCategoryName(currentApprovalReceivable?.receivablesManagementType || 0) }}
            </el-descriptions-item>
            <el-descriptions-item label="最后付款日">
              {{ formatTime(currentApprovalReceivable?.lastPaymentDate || null) }}
            </el-descriptions-item>
            <el-descriptions-item label="付款方">
              {{ currentApprovalReceivable?.payer || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="收款方">
              {{ currentApprovalReceivable?.recipients || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="应收金额">
              <span class="amount-text">{{
                formatCurrency(currentApprovalReceivable?.amountReceivable || 0)
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="付款次数">
              {{ currentApprovalReceivable?.numberOfPayments || 0 }}
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions
            v-if="currentApprovalReceivable?.remark"
            title="备注信息"
            :column="1"
            border
            style="margin-top: 20px"
          >
            <el-descriptions-item label="备注">
              {{ currentApprovalReceivable.remark }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 审批操作表单 -->
        <div class="approval-form">
          <h4>审批操作</h4>
          <el-form
            :model="approvalForm"
            :rules="approvalRules"
            ref="approvalFormRef"
            label-width="100px"
          >
            <el-form-item label="备注" prop="reason">
              <el-input
                v-model="approvalForm.reason"
                type="textarea"
                :rows="4"
                placeholder="请输入备注（必填）"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleApprovalClose">取消</el-button>
          <el-button
            type="success"
            @click="handleApprove"
            :loading="approvalSubmitting"
            :disabled="!canApprove"
          >
            审核通过
          </el-button>
          <el-button
            type="danger"
            @click="handleReject"
            :loading="approvalSubmitting"
            :disabled="!canApprove"
          >
            审核不通过
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 收款弹窗 -->
    <el-dialog :title="'新增实付'" v-model="receiveDialogVisible" width="900px">
      <!-- 显示应收账款信息 -->
      <div
        v-if="currentReceivableRow"
        style="
          background: #f5f7fa;
          padding: 15px;
          margin-bottom: 20px;
          border-radius: 4px;
        "
      >
        <div
          style="
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
          "
        >
          <span
            ><strong>应收金额：</strong
            >{{ currentReceivableRow.amountReceivable || 0 }} 元</span
          >
          <span
            ><strong>已收金额：</strong
            >{{ currentReceivableRow.paidInAmount || 0 }} 元</span
          >
          <span
            ><strong>剩余金额：</strong
            >{{
              (currentReceivableRow.amountReceivable || 0) -
              (currentReceivableRow.paidInAmount || 0)
            }}
            元</span
          >
        </div>
        <div style="color: #e6a23c; font-size: 14px">
          <i class="el-icon-warning"></i> 提示：实收金额不能超过应收金额
        </div>
      </div>

      <el-form
        :model="receiveForm"
        label-width="90px"
        ref="receiveFormRef"
        :rules="receiveRules"
      >
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="流水号">
              <el-input v-model="receiveForm.flowingWaterNumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款机构">
              <el-input v-model="receiveForm.paymentInstitutions" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款方式" prop="paymentMethod">
              <el-select
                v-model="receiveForm.paymentMethod"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.financialCategoryId"
                  :label="item.categoryName"
                  :value="item.categoryName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后付款日" prop="lastPaymentDate">
              <el-date-picker
                v-model="receiveForm.lastPaymentDate"
                type="datetime"
                placeholder="选择日期时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款金额" prop="amount">
              <el-input-number
                v-model="receiveForm.amount"
                :min="0"
                :max="
                  currentReceivableRow
                    ? (currentReceivableRow.amountReceivable || 0) -
                      (currentReceivableRow.paidInAmount || 0)
                    : undefined
                "
                style="width: 100%"
                @change="validatePaymentAmount"
              />
              <div
                v-if="paymentAmountError"
                style="color: #f56c6c; font-size: 12px; margin-top: 5px"
              >
                {{ paymentAmountError }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="receiveForm.remark" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="receiveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReceiveForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Plus, Download } from "@element-plus/icons-vue";
import * as XLSX from "xlsx";
import http from "@/http/axiosHelper";
import { finread, finwrite } from "@/systeamaxios/sysaxiosHelpers";

// 类型定义
interface CategoryOption {
  financialCategoryId: number;
  categoryName: string;
}

interface ReceivableRow {
  receivablesManagementId: number;
  flowingWaterNumber: string;
  receivablesManagementName: string;
  receivablesManagementType: number;
  amountReceivable: number;
  paidInAmount: number;
  remainingAmount: number;
  recipients: string;
  payer: string;
  numberOfPayments: number;
  paymentInstitutions?: string;
  remark: string;
  creatTime: string;
  creatName: string;
  updateTime?: string;
  updateName?: string;
  deleteTime?: string;
  deleteName?: string;
  lastPaymentDate?: string | null;
  state: number;
  isDel: boolean;
}

// 统一的日期处理函数
function formatDateForApi(dateValue: string | Date | null): string | null {
  if (!dateValue) return null;

  try {
    const date = new Date(dateValue);
    if (isNaN(date.getTime())) return null;
    return date.toISOString();
  } catch (error) {
    console.error("日期格式化错误:", error, "原始值:", dateValue);
    return null;
  }
}

// 接口基础路径
const API_BASE = {
  show: "/finread/api/FinancialCategory/ShowReceivablesManagementCommand",
  add: "/finwrite/api/ReceivablesManagement/AddReceivablesManagementCommand",
  update: "/finwrite/api/ReceivablesManagement/UpdReceivablesManagementCommand",
  delete: "/finwrite/api/ReceivablesManagement/DelReceivablesManagementCommand",
  categories: "/finread/api/FinancialCategory/SelectFinancialCategoryCommand",
};
/*const API_BASE = {
  show: "/api/FinancialCategory/ShowReceivablesManagementCommand",
  add: "/api/ReceivablesManagement/AddReceivablesManagementCommand",
  update: "/api/ReceivablesManagement/UpdReceivablesManagementCommand",
  delete: "/api/ReceivablesManagement/DelReceivablesManagementCommand",
  categories: "/api/FinancialCategory/SelectFinancialCategoryCommand",
};*/

// 获取当前登录用户名
const getCurrentUserName = (): string => {
  const userName = localStorage.getItem("userName") || localStorage.getItem("currentUser") || "admin";
  console.log("Getting current userName:", userName);
  return userName;
};

// 获取当前用户的rid
const getCurrentRid = (): number => {
  const storedRid = localStorage.getItem("Rid");
  const rid = storedRid !== null ? Number(storedRid) : 2;
  console.log("Getting current rid:", rid, "stored value:", storedRid);
  return rid;
};

interface SearchForm {
  PageIndex: number;
  PageSize: number;
  FlowingWaterNumber: string;
  PayableManagementName: string;
  PayableManagementType: number | null;
  Payer: string;
  STime: string | null;
  ETime: string | null;
  State: number | null;
  rid?: number;
  creatName?: string;
}

const searchForm = reactive<SearchForm>({
  PageIndex: 1,
  PageSize: 15, // 修改默认分页为15条
  FlowingWaterNumber: "",
  PayableManagementName: "",
  PayableManagementType: null,
  Payer: "",
  STime: null,
  ETime: null,
  State: null,
  rid: undefined,
  creatName: undefined,
});

const tableData = ref<ReceivableRow[]>([]);
const total = ref(0);
const loading = ref(false);
const exportLoading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("新增");
const formRef = ref<any>();
interface FormData {
  receivablesManagementId: number;
  flowingWaterNumber: string;
  receivablesManagementName: string;
  receivablesManagementType: number;
  payer: string;
  amountReceivable: number;
  paidInAmount: number;
  remainingAmount: number;
  state: number;
  lastPaymentDate: string | null;
  recipients: string;
  numberOfPayments: number;
  remark: string;
  creatTime: string;
  creatName: string;
  updateTime: string;
  updateName: string;
  deleteTime: string;
  deleteName: string;
  isDel: boolean;
  paymentInstitutions: string;
}

const formData = reactive<FormData>({
  receivablesManagementId: 0,
  flowingWaterNumber: "",
  receivablesManagementName: "",
  receivablesManagementType: undefined as any,
  payer: "",
  amountReceivable: 0,
  paidInAmount: 0,
  remainingAmount: 0,
  state: 0,
  lastPaymentDate: null,
  recipients: "",
  numberOfPayments: 0,
  remark: "",
  creatTime: "",
  creatName: "",
  updateTime: "",
  updateName: "",
  deleteTime: "",
  deleteName: "",
  isDel: false,
  paymentInstitutions: "",
});

const rules = {
  flowingWaterNumber: [
    { required: true, message: "请输入流水号", trigger: "blur" },
  ],
  receivablesManagementName: [
    { required: true, message: "请输入名称", trigger: "blur" },
  ],
  receivablesManagementType: [
    { required: true, message: "请选择类别", trigger: "change" },
  ],
  payer: [{ required: true, message: "请输入付款方", trigger: "blur" }],
  recipients: [{ required: true, message: "请输入收款方", trigger: "blur" }],
  amountReceivable: [
    { required: true, message: "请输入应收金额", trigger: "blur" },
    {
      type: "number",
      min: 0.01,
      message: "应收金额必须大于0",
      trigger: "blur",
    },
  ],
};

// 收款表单验证规则
const receiveRules = {
  paymentMethod: [
    { required: true, message: "请选择付款方式", trigger: "change" },
  ],
  amount: [
    { required: true, message: "请输入付款金额", trigger: "blur" },
    {
      validator: (_: any, value: any, callback: any) => {
        if (!value || value <= 0) {
          callback(new Error("付款金额必须大于0"));
        } else if (currentReceivableRow.value) {
          const amountReceivable =
            currentReceivableRow.value.amountReceivable || 0;
          const currentPaidAmount =
            currentReceivableRow.value.paidInAmount || 0;
          const remainingAmount = amountReceivable - currentPaidAmount;
          if (value > remainingAmount) {
            callback(
              new Error(`付款金额不能超过剩余金额 ${remainingAmount} 元`)
            );
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 1. 下拉数据变量
const categoryOptions = ref<CategoryOption[]>([]);

// 新增变量
const dateRange = ref<[Date, Date] | null>(null);
const MAX_PAYMENT_TIMES = 10; // 最大收款次数限制

// 2. 获取类别下拉数据（同时用于分类和付款方式）
async function getCategoryOptions() {
  try {
    const res = await http.get(API_BASE.categories);
    categoryOptions.value = res.data.data || [];
  } catch (error: any) {
    console.error("获取分类数据失败:", error);
    ElMessage.error("获取分类数据失败");
  }
}

// 根据分类ID获取分类名称
function getCategoryName(categoryId: number): string {
  if (!categoryId) return "-";
  const category = categoryOptions.value.find(
    (item) => item.financialCategoryId === categoryId
  );
  return category ? category.categoryName : "-";
}

function resetFormData() {
  Object.assign(formData, {
    receivablesManagementId: 0,
    flowingWaterNumber: "",
    receivablesManagementName: "",
    receivablesManagementType: undefined,
    payer: "",
    amountReceivable: 0,
    paidInAmount: 0,
    remainingAmount: 0,
    state: 0,
    lastPaymentDate: null,
    recipients: "",
    numberOfPayments: 0,
    remark: "",
    creatTime: "",
    creatName: "",
    updateTime: "",
    updateName: "",
    deleteTime: "",
    deleteName: "",
    isDel: false,
    paymentInstitutions: "",
  });
}

// 搜索处理
const handleSearch = () => {
  searchForm.PageIndex = 1;
  getList();
};

// 重置搜索
const handleReset = () => {
  // 权限控制：RID != 2的用户只能看到自己创建的数据，RID == 2的用户可以看到所有人的数据
  const currentRid = getCurrentRid();
  const currentUserName = getCurrentUserName();
  
  let ridParam: number | undefined;
  let creatNameParam: string | undefined;
  if (currentRid === 2) {
    // 管理员用户(rid==2)可以查看所有数据
    ridParam = undefined;
    creatNameParam = undefined;
  } else {
    // 其他角色用户，只能查看自己创建的数据
    ridParam = currentRid;
    creatNameParam = currentUserName;
  }
  
  Object.assign(searchForm, {
    PageIndex: 1,
    PageSize: 15, // 修改默认分页为15条
    FlowingWaterNumber: "",
    PayableManagementName: "",
    PayableManagementType: null,
    Payer: "",
    STime: null,
    ETime: null,
    State: null,
    rid: ridParam,
    creatName: creatNameParam,
  });
  dateRange.value = null;
  getList();
};

// 新增按钮
const handleAdd = () => {
  // 权限验证：RID == 2的用户不能新增，其他用户可以新增
  if (getCurrentRid() === 2) {
    ElMessage.error("您没有新增权限");
    return;
  }
  openDialog();
};

// 导出功能
const handleExport = async () => {
  if (!tableData.value.length) {
    ElMessage.warning('暂无数据可导出');
    return;
  }
  
  exportLoading.value = true;
  try {
    const exportData = formatDataForExport(tableData.value);
    const workbook = generateWorkbook(exportData);
    const filename = generateFilename();
    downloadExcelFile(workbook, filename);
    ElMessage.success('导出成功');
  } catch (error) {
    handleExportError(error, 'export');
  } finally {
    exportLoading.value = false;
  }
};

// 导出列配置
const exportColumns = [
  { key: 'flowingWaterNumber', header: '流水号' },
  { key: 'receivablesManagementName', header: '名称' },
  { key: 'categoryName', header: '分类' },
  { key: 'recipients', header: '收款方' },
  { key: 'amountReceivable', header: '应收金额' },
  { key: 'paidInAmount', header: '实收金额' },
  { key: 'remainingAmount', header: '剩余金额' },
  { key: 'stateText', header: '状态' },
  { key: 'creatTime', header: '创建时间' }
];

// 格式化数据用于导出
const formatDataForExport = (data: ReceivableRow[]) => {
  return data.map(row => ({
    flowingWaterNumber: row.flowingWaterNumber || '-',
    receivablesManagementName: row.receivablesManagementName || '-',
    categoryName: getCategoryName(row.receivablesManagementType),
    recipients: row.recipients || '-',
    amountReceivable: row.amountReceivable || 0,
    paidInAmount: row.paidInAmount || 0,
    remainingAmount: row.remainingAmount || 0,
    stateText: formatState(row.state),
    creatTime: formatTime(row.creatTime)
  }));
};

// 生成Excel工作簿
const generateWorkbook = (data: any[]) => {
  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  
  // 准备表头
  const headers = exportColumns.map(col => col.header);
  
  // 准备数据行
  const rows = data.map(row => 
    exportColumns.map(col => row[col.key])
  );
  
  // 合并表头和数据
  const worksheetData = [headers, ...rows];
  
  // 创建工作表
  const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
  
  // 设置列宽
  const colWidths = exportColumns.map(col => {
    switch (col.key) {
      case 'flowingWaterNumber':
        return { wch: 20 };
      case 'receivablesManagementName':
        return { wch: 25 };
      case 'categoryName':
        return { wch: 15 };
      case 'recipients':
        return { wch: 15 };
      case 'amountReceivable':
      case 'paidInAmount':
      case 'remainingAmount':
        return { wch: 12 };
      case 'stateText':
        return { wch: 10 };
      case 'creatTime':
        return { wch: 20 };
      default:
        return { wch: 15 };
    }
  });
  worksheet['!cols'] = colWidths;
  
  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, '应收账款管理');
  
  return workbook;
};

// 生成文件名
const generateFilename = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  
  return `应收账款管理_${year}${month}${day}_${hours}${minutes}${seconds}.xlsx`;
};

// 下载Excel文件
const downloadExcelFile = (workbook: any, filename: string) => {
  // 生成Excel文件的二进制数据
  const excelBuffer = XLSX.write(workbook, { 
    bookType: 'xlsx', 
    type: 'array' 
  });
  
  // 创建Blob对象
  const blob = new Blob([excelBuffer], { 
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
  });
  
  // 创建下载链接
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  
  // 触发下载
  document.body.appendChild(link);
  link.click();
  
  // 清理
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

// 导出错误处理
const handleExportError = (error: any, context: string) => {
  console.error(`Export error in ${context}:`, error);
  exportLoading.value = false;
  
  let message = '导出失败，请重试';
  if (error && error.message) {
    if (error.message.includes('no data')) {
      message = '暂无数据可导出';
    } else if (error.message.includes('generation')) {
      message = '文件生成失败，请检查浏览器兼容性';
    } else if (error.message.includes('download')) {
      message = '文件下载失败，请重试';
    }
  }
  
  ElMessage.error(message);
};

// 日期范围变化处理
const handleDateChange = (dates: [Date, Date] | null) => {
  if (dates) {
    searchForm.STime = dates[0].toISOString().split('T')[0];
    searchForm.ETime = dates[1].toISOString().split('T')[0];
  } else {
    searchForm.STime = null;
    searchForm.ETime = null;
  }
};

// 编辑处理
const handleEdit = (row: any) => {
  // 权限验证：RID == 2的用户不能编辑，其他用户可以编辑
  if (getCurrentRid() === 2) {
    ElMessage.error("您没有编辑权限");
    return;
  }
  openDialog(row);
};

// 查看处理
const handleView = (row: any) => {
  // 查看功能，设置为只读模式
  openDialog(row);
  // TODO: 添加只读模式逻辑
};

// 删除处理
const handleDelete = (id: number) => {
  // 权限验证：RID == 2的用户不能删除，其他用户可以删除
  if (getCurrentRid() === 2) {
    ElMessage.error("您没有删除权限");
    return;
  }
  // 根据id找到对应的行数据
  const row = tableData.value.find(item => item.receivablesManagementId === id);
  if (row) {
    delRow(row);
  }
};

// 审批处理
const handleApproval = (row: ReceivableRow) => {
  currentApprovalReceivable.value = row;

  // 重置审批表单
  approvalForm.reason = "";
  approvalFormRef.value?.clearValidate();

  approvalDialogVisible.value = true;
};

// 处理审批通过
const handleApprove = async () => {
  if (!currentApprovalReceivable.value) return;

  try {
    await approvalFormRef.value?.validate();

    await ElMessageBox.confirm("确认审批通过该收款申请吗？", "确认审批", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "success",
    });

    approvalSubmitting.value = true;

    // 调用审批通过API
    const approvalData = {
      receivablesManagementId: currentApprovalReceivable.value.receivablesManagementId,
      flowingWaterNumber: currentApprovalReceivable.value.flowingWaterNumber,
      receivablesManagementName: currentApprovalReceivable.value.receivablesManagementName,
      receivablesManagementType: currentApprovalReceivable.value.receivablesManagementType,
      payer: currentApprovalReceivable.value.payer,
      amountReceivable: currentApprovalReceivable.value.amountReceivable,
      paidInAmount: currentApprovalReceivable.value.paidInAmount,
      remainingAmount: currentApprovalReceivable.value.remainingAmount,
      state: 1, // 审批通过，状态改为审批成功
      lastPaymentDate: currentApprovalReceivable.value.lastPaymentDate,
      recipients: currentApprovalReceivable.value.recipients,
      numberOfPayments: currentApprovalReceivable.value.numberOfPayments,
      remark: approvalForm.reason, // 使用审批意见作为备注
      creatTime: currentApprovalReceivable.value.creatTime,
      creatName: currentApprovalReceivable.value.creatName,
      updateTime: new Date().toISOString(),
      updateName: "admin",
      paymentInstitutions: currentApprovalReceivable.value.paymentInstitutions || null,
      isDel: currentApprovalReceivable.value.isDel,
    };

    const response = await http.post(API_BASE.update, approvalData);

    if (response.data.code === 200) {
      // 更新本地数据状态
      const index = tableData.value.findIndex(
        (item) =>
          item.receivablesManagementId ===
          currentApprovalReceivable.value!.receivablesManagementId
      );
      if (index !== -1) {
        tableData.value[index].state = 1; // 审批通过，状态改为审批成功
        tableData.value[index].remark = approvalForm.reason; // 保存备注
        tableData.value[index].updateTime = new Date().toISOString();
        tableData.value[index].updateName = "admin";
      }
    } else {
      throw new Error(response.data.message || "审批失败");
    }

    ElMessage.success("审批通过成功");
    handleApprovalClose();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error("审批失败");
    }
  } finally {
    approvalSubmitting.value = false;
  }
};

// 处理审批拒绝
const handleReject = async () => {
  if (!currentApprovalReceivable.value) return;

  try {
    await approvalFormRef.value?.validate();

    await ElMessageBox.confirm("确认拒绝该收款申请吗？", "确认拒绝", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    });

    approvalSubmitting.value = true;

    // 调用审批拒绝API
    const approvalData = {
      receivablesManagementId: currentApprovalReceivable.value.receivablesManagementId,
      flowingWaterNumber: currentApprovalReceivable.value.flowingWaterNumber,
      receivablesManagementName: currentApprovalReceivable.value.receivablesManagementName,
      receivablesManagementType: currentApprovalReceivable.value.receivablesManagementType,
      payer: currentApprovalReceivable.value.payer,
      amountReceivable: currentApprovalReceivable.value.amountReceivable,
      paidInAmount: currentApprovalReceivable.value.paidInAmount,
      remainingAmount: currentApprovalReceivable.value.remainingAmount,
      state: 2, // 审批拒绝
      lastPaymentDate: currentApprovalReceivable.value.lastPaymentDate,
      recipients: currentApprovalReceivable.value.recipients,
      numberOfPayments: currentApprovalReceivable.value.numberOfPayments,
      remark: approvalForm.reason, // 使用审批意见作为备注
      creatTime: currentApprovalReceivable.value.creatTime,
      creatName: currentApprovalReceivable.value.creatName,
      updateTime: new Date().toISOString(),
      updateName: "admin",
      paymentInstitutions: currentApprovalReceivable.value.paymentInstitutions || null,
      isDel: currentApprovalReceivable.value.isDel,
    };

    const response = await http.post(API_BASE.update, approvalData);

    if (response.data.code === 200) {
      // 更新本地数据状态
      const index = tableData.value.findIndex(
        (item) =>
          item.receivablesManagementId ===
          currentApprovalReceivable.value!.receivablesManagementId
      );
      if (index !== -1) {
        tableData.value[index].state = 2; // 审批拒绝
        tableData.value[index].remark = approvalForm.reason; // 保存备注
        tableData.value[index].updateTime = new Date().toISOString();
        tableData.value[index].updateName = "admin";
      }
    } else {
      throw new Error(response.data.message || "审批失败");
    }

    ElMessage.success("审批拒绝成功");
    handleApprovalClose();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error("审批失败");
    }
  } finally {
    approvalSubmitting.value = false;
  }
};

// 关闭审批对话框
const handleApprovalClose = () => {
  approvalDialogVisible.value = false;
  currentApprovalReceivable.value = null;
  approvalForm.reason = "";
  approvalFormRef.value?.clearValidate();
};

// 收款处理
const handlePayment = (row: any) => {
  openReceiveDialog(row);
};

// 检查是否可以继续收款
const canContinuePayment = (row: any): boolean => {
  const currentPaymentTimes = row.numberOfPayments || 0;
  return currentPaymentTimes < MAX_PAYMENT_TIMES;
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  searchForm.PageSize = size;
  searchForm.PageIndex = 1;
  // 权限控制：保持当前用户的权限设置
  const currentRid = getCurrentRid();
  const currentUserName = getCurrentUserName();
  if (currentRid === 2) {
    searchForm.rid = undefined;
    searchForm.creatName = undefined;
  } else {
    searchForm.rid = currentRid;
    searchForm.creatName = currentUserName;
  }
  getList();
};

// 页码变化
const handlePageChange = (page: number) => {
  searchForm.PageIndex = page;
  // 权限控制：保持当前用户的权限设置
  const currentRid = getCurrentRid();
  const currentUserName = getCurrentUserName();
  if (currentRid === 2) {
    searchForm.rid = undefined;
    searchForm.creatName = undefined;
  } else {
    searchForm.rid = currentRid;
    searchForm.creatName = currentUserName;
  }
  getList();
};

async function getList() {
  loading.value = true;
  try {
    // 权限控制：RID == 2的用户可以看到所有人的数据，其他用户只能看到自己创建的数据
    const currentRid = getCurrentRid();
    const currentUserName = getCurrentUserName();
    
    if (currentRid === 2) {
      // 管理员用户(rid==2)可以查看所有数据
      searchForm.rid = undefined;
      searchForm.creatName = undefined;
    } else {
      // 其他角色用户，只能查看自己创建的数据
      searchForm.rid = currentRid;
      searchForm.creatName = currentUserName;
    }

    console.log("当前用户RID:", currentRid);
    console.log("当前用户名:", currentUserName);
    console.log("查询参数:", searchForm);

    const res = await http.get(API_BASE.show, {
      params: {
        PageIndex: searchForm.PageIndex,
        PageSize: searchForm.PageSize,
        FlowingWaterNumber: searchForm.FlowingWaterNumber,
        PayableManagementName: searchForm.PayableManagementName,
        PayableManagementType: searchForm.PayableManagementType,
        Payer: searchForm.Payer,
        STime: searchForm.STime,
        ETime: searchForm.ETime,
        State: searchForm.State,
        rid: searchForm.rid,
        creatName: searchForm.creatName,
      },
    });
    tableData.value = res.data.pageDatas || [];
    total.value = res.data.totalCount || 0;
    ElMessage.success(res.data.message || "数据加载成功");
  } catch (error: any) {
    console.error("获取列表数据失败:", error);
    ElMessage.error("获取列表数据失败");
  } finally {
    loading.value = false;
  }
}

function resetSearch() {
  // 权限控制：RID == 2的用户可以看到所有人的数据，其他用户只能看到自己创建的数据
  const currentRid = getCurrentRid();
  const currentUserName = getCurrentUserName();
  
  if (currentRid === 2) {
    // 管理员用户(rid==2)可以查看所有数据
    searchForm.rid = undefined;
    searchForm.creatName = undefined;
  } else {
    // 其他角色用户，只能查看自己创建的数据
    searchForm.rid = currentRid;
    searchForm.creatName = currentUserName;
  }
  
  searchForm.FlowingWaterNumber = "";
  searchForm.PayableManagementName = "";
  searchForm.PayableManagementType = null;
  searchForm.Payer = "";
  searchForm.STime = null;
  searchForm.ETime = null;
  searchForm.State = null;
  searchForm.PageIndex = 1;
  getList();
}

function generateFlowingWaterNumber() {
  // 例如：RW20250725153000123
  const now = new Date();
  const pad = (n: number) => n.toString().padStart(2, "0");
  const y = now.getFullYear();
  const m = pad(now.getMonth() + 1);
  const d = pad(now.getDate());
  const h = pad(now.getHours());
  const min = pad(now.getMinutes());
  const s = pad(now.getSeconds());
  const ms = now.getMilliseconds().toString().padStart(3, "0");
  return `RW${y}${m}${d}${h}${min}${s}${ms}`;
}

function openDialog(row?: ReceivableRow) {
  getCategoryOptions();
  if (row) {
    dialogTitle.value = "编辑";
    Object.assign(formData, row);
    // 编辑时如果没有 updateTime，赋当前时间
    if (!formData.updateTime) {
      formData.updateTime = new Date().toISOString().slice(0, 19);
    }
    // 编辑时如果没有 deleteTime，赋当前时间
    if (!formData.deleteTime) {
      formData.deleteTime = new Date().toISOString().slice(0, 19);
    }
  } else {
    dialogTitle.value = "新增";
    resetFormData();
    formData.flowingWaterNumber = generateFlowingWaterNumber();
    formData.creatName = "admin";
    formData.creatTime = new Date().toISOString().slice(0, 19);
    formData.updateTime = new Date().toISOString().slice(0, 19);
    // 新增时赋当前时间
    formData.deleteTime = new Date().toISOString().slice(0, 19);
  }
  dialogVisible.value = true;
}

function submitForm() {
  // 权限验证：RID == 2的用户不能提交表单，其他用户可以提交
  if (getCurrentRid() === 2) {
    ElMessage.error("您没有操作权限");
    return;
  }
  
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    try {
      // 处理日期格式
      const formattedLastPaymentDate = formatDateForApi(
        formData.lastPaymentDate
      );

      // 准备提交数据
      const submitData = {
        receivablesManagementId: formData.receivablesManagementId || 0,
        flowingWaterNumber: formData.flowingWaterNumber?.trim() || "",
        receivablesManagementName:
          formData.receivablesManagementName?.trim() || "",
        receivablesManagementType:
          Number(formData.receivablesManagementType) || 0,
        payer: formData.payer?.trim() || "",
        amountReceivable: Number(formData.amountReceivable) || 0,
        paidInAmount: Number(formData.paidInAmount) || 0,
        remainingAmount: Number(formData.remainingAmount) || 0,
        state: Number(formData.state) || 0,
        lastPaymentDate: formattedLastPaymentDate,
        recipients: formData.recipients?.trim() || "",
        numberOfPayments: Number(formData.numberOfPayments) || 0,
        remark: formData.remark?.trim() || "",
        creatTime: formData.receivablesManagementId
          ? formData.creatTime
          : new Date().toISOString(),
        creatName: formData.receivablesManagementId
          ? formData.creatName
          : "admin",
        updateTime: formData.receivablesManagementId
          ? new Date().toISOString()
          : null,
        updateName: formData.receivablesManagementId ? "admin" : null,
        paymentInstitutions: formData.paymentInstitutions?.trim() || null,
        isDel: false,
      };

      // 验证必填字段
      if (!submitData.flowingWaterNumber) {
        ElMessage.error("流水号不能为空");
        return;
      }
      if (!submitData.receivablesManagementName) {
        ElMessage.error("名称不能为空");
        return;
      }
      if (!submitData.receivablesManagementType) {
        ElMessage.error("请选择类别");
        return;
      }
      if (!submitData.payer) {
        ElMessage.error("付款方不能为空");
        return;
      }
      if (!submitData.recipients) {
        ElMessage.error("收款方不能为空");
        return;
      }
      if (submitData.amountReceivable <= 0) {
        ElMessage.error("应收金额必须大于0");
        return;
      }

      console.log("提交数据:", submitData);

      if (formData.receivablesManagementId) {
        // 修改
        await http.post(API_BASE.update, submitData);
        ElMessage.success("修改成功");
      } else {
        // 新增
        await http.post(API_BASE.add, submitData);
        ElMessage.success("新增成功");
      }
      dialogVisible.value = false;
      getList();
    } catch (error: any) {
      console.error("提交失败:", error);
      console.error("错误详情:", error.response?.data);

      let errorMessage = "操作失败，请重试";
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.response?.status === 400) {
        errorMessage = "请求数据格式错误，请检查输入信息";
      }

      ElMessage.error(errorMessage);
    }
  });
}

function delRow(row: ReceivableRow) {
  ElMessageBox.confirm("确定删除该条数据吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      await http.post(
        `${API_BASE.delete}?ReceivablesManagementId=${row.receivablesManagementId}`
      );
      ElMessage.success("删除成功");
      getList();
    } catch (error: any) {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  });
}

// 审批相关数据
const approvalDialogVisible = ref(false);
const currentApprovalReceivable = ref<ReceivableRow | null>(null);
const approvalFormRef = ref();
const approvalSubmitting = ref(false);

// 审批表单
const approvalForm = reactive({
  reason: "",
});

// 审批表单验证规则
const approvalRules = {
  reason: [
    { required: true, message: "请输入备注", trigger: "blur" },
    { min: 2, message: "备注至少2个字符", trigger: "blur" },
  ],
};

// 计算属性 - 是否可以审批
const canApprove = computed(() => {
  return currentApprovalReceivable.value?.state === 0;
});

const receiveDialogVisible = ref(false);
const receiveFormRef = ref<any>();
const receiveForm = ref({
  flowingWaterNumber: "",
  paymentInstitutions: "",
  paymentMethod: "",
  lastPaymentDate: null as string | null,
  amount: 0,
  remark: "",
});

// 当前选中行的数据，用于验证
const currentReceivableRow = ref<ReceivableRow | null>(null);

// 付款金额验证错误信息
const paymentAmountError = ref("");

function openReceiveDialog(row: ReceivableRow) {
  // 保存当前行数据用于验证
  currentReceivableRow.value = row;

  // 获取分类选项（用于付款方式）
  getCategoryOptions();

  receiveForm.value = {
    flowingWaterNumber: row.flowingWaterNumber,
    paymentInstitutions: row.paymentInstitutions || "", // 反填付款机构
    paymentMethod: "",
    lastPaymentDate: row.lastPaymentDate || new Date().toISOString().slice(0, 19), // 反填最后付款日，如果没有则使用当前时间
    amount: 0,
    remark: "",
  };

  // 清空错误信息
  paymentAmountError.value = "";

  receiveDialogVisible.value = true;
}

// 验证付款金额
function validatePaymentAmount() {
  paymentAmountError.value = "";

  if (!currentReceivableRow.value) return;

  const amountReceivable = currentReceivableRow.value.amountReceivable || 0;
  const currentPaidAmount = currentReceivableRow.value.paidInAmount || 0;
  const newPaymentAmount = receiveForm.value.amount || 0;
  const remainingAmount = amountReceivable - currentPaidAmount;

  if (newPaymentAmount > remainingAmount) {
    paymentAmountError.value = `付款金额不能超过剩余金额 ${remainingAmount} 元`;
  } else if (newPaymentAmount <= 0) {
    paymentAmountError.value = "付款金额必须大于0";
  }
}

function submitReceiveForm() {
  // 使用表单验证
  receiveFormRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }

    try {
      // 验证必要数据
      if (
        !currentReceivableRow.value ||
        !currentReceivableRow.value.receivablesManagementId
      ) {
        ElMessage.error("无法获取应收账款信息");
        return;
      }

      // 计算新的实收金额和剩余金额
      const currentPaidAmount =
        Number(currentReceivableRow.value.paidInAmount) || 0;
      const newPaymentAmount = Number(receiveForm.value.amount) || 0;
      const newPaidInAmount = currentPaidAmount + newPaymentAmount;
      const amountReceivable =
        Number(currentReceivableRow.value.amountReceivable) || 0;
      const newRemainingAmount = Math.max(
        0,
        amountReceivable - newPaidInAmount
      ); // 确保不为负数

      // 数据验证
      if (amountReceivable <= 0) {
        ElMessage.error("应收金额数据异常");
        return;
      }

      if (newPaymentAmount <= 0) {
        ElMessage.error("付款金额必须大于0");
        return;
      }

      if (newPaidInAmount > amountReceivable) {
        ElMessage.error("实收金额不能超过应收金额");
        return;
      }

      // 检查数据合理性
      if (amountReceivable > 100000) {
        ElMessage.warning("应收金额过大，请确认数据是否正确");
      }

      // 准备提交数据，使用修改应收账款的API（格式与正常编辑保持一致）
      const submitData = {
        receivablesManagementId:
          Number(currentReceivableRow.value.receivablesManagementId) || 0,
        flowingWaterNumber:
          (currentReceivableRow.value.flowingWaterNumber || "")
            .toString()
            .trim() || "",
        receivablesManagementName:
          (currentReceivableRow.value.receivablesManagementName || "")
            .toString()
            .trim() || "",
        receivablesManagementType:
          Number(currentReceivableRow.value.receivablesManagementType) || 0,
        payer: (currentReceivableRow.value.payer || "").toString().trim() || "",
        amountReceivable: Number(amountReceivable.toFixed(2)),
        paidInAmount: Number(newPaidInAmount.toFixed(2)), // 更新实收金额
        remainingAmount: Number(newRemainingAmount.toFixed(2)), // 更新剩余金额
        state:
          Number(
            newRemainingAmount <= 0
              ? 1
              : newPaidInAmount > 0
              ? 3
              : currentReceivableRow.value.state
          ) || 0,
        lastPaymentDate: formatDateForApi(receiveForm.value.lastPaymentDate),
        recipients:
          (currentReceivableRow.value.recipients || "").toString().trim() || "",
        numberOfPayments:
          Number((currentReceivableRow.value.numberOfPayments || 0) + 1) || 1,
        remark:
          (receiveForm.value.remark || currentReceivableRow.value.remark || "")
            .toString()
            .trim() || "",
        creatTime:
          currentReceivableRow.value.creatTime || new Date().toISOString(),
        creatName:
          (currentReceivableRow.value.creatName || "admin").toString().trim() ||
          "admin",
        updateTime: new Date().toISOString(),
        updateName: "admin",
        paymentInstitutions:
          (
            receiveForm.value.paymentInstitutions ||
            currentReceivableRow.value.paymentInstitutions ||
            ""
          )
            .toString()
            .trim() || "",
        isDel: false,
      };

      // 验证必填字段
      if (
        !submitData.receivablesManagementId ||
        !submitData.flowingWaterNumber ||
        !submitData.receivablesManagementName
      ) {
        ElMessage.error("缺少必填字段信息");
        console.error("缺少必填字段:", {
          receivablesManagementId: submitData.receivablesManagementId,
          flowingWaterNumber: submitData.flowingWaterNumber,
          receivablesManagementName: submitData.receivablesManagementName,
        });
        return;
      }

      // 调用修改应收账款API
      // 调试信息
      console.log("收款提交数据:", submitData);

      // 验证数据完整性
      const requiredFields = [
        "receivablesManagementId",
        "flowingWaterNumber",
        "receivablesManagementName",
      ];
      const missingFields = requiredFields.filter(
        (field) => !(submitData as any)[field]
      );
      if (missingFields.length > 0) {
        console.error("缺少必填字段:", missingFields);
        ElMessage.error(`缺少必填字段: ${missingFields.join(", ")}`);
        return;
      }
      const response = await http.post(API_BASE.update, submitData);
      console.log("收款响应:", response);

      receiveDialogVisible.value = false;
      ElMessage.success("收款成功");

      // 刷新列表
      getList();
    } catch (error: any) {
      console.error("收款失败:", error);
      console.error("错误详情:", error.response?.data);

      let errorMessage = "收款失败，请重试";
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.response?.status === 400) {
        errorMessage = "请求数据格式错误，请检查输入信息";
      }

      ElMessage.error(errorMessage);
    }
  });
}

// 状态格式化函数
const formatState = (state: number) => {
  const stateMap: { [key: number]: string } = {
    0: "未审批",
    1: "审批成功",
    2: "已驳回",
    5: "未收款",
    6: "部分收款",
    7: "已收清",
  };
  return stateMap[state] || "-";
};

const getStateTagType = (state: number) => {
  const tagTypeMap: { [key: number]: string } = {
    0: "warning", // 未审批 - 警告色
    1: "success", // 审批成功 - 成功色
    2: "danger", // 已驳回 - 危险色
    5: "info", // 未收款 - 信息色
    6: "primary", // 部分收款 - 主要色
    7: "success", // 已收清 - 成功色
  };
  return tagTypeMap[state] || "";
};

// 格式化货币
const formatCurrency = (amount: number) => {
  return new Intl.NumberFormat("zh-CN", {
    style: "currency",
    currency: "CNY",
  }).format(amount);
};

// 格式化空值
const formatNullValue = (value: any) => {
  return value === null || value === undefined || value === "" ? "-" : value;
};

// 格式化时间
const formatTime = (time: string | null) => {
  if (!time) return "-";
  try {
    return new Date(time).toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
  } catch {
    return time;
  }
};

onMounted(() => {
  getList();
  getCategoryOptions();
});
</script>

<style scoped>
.receivable-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-box {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.action-box {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
  text-align: right;
}

.custom-header {
  text-align: center;
  font-weight: bold;
  background: #fafafa;
}

.custom-cell {
  text-align: center;
}

/* 表格样式 */
:deep(.el-table) {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__header) {
  background-color: #f8f9fa;
}

:deep(.el-table th) {
  background-color: #f8f9fa !important;
  color: #333;
  font-weight: 600;
}

/* 分页样式 */
:deep(.el-pagination) {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

/* 按钮样式 */
.el-button + .el-button {
  margin-left: 8px;
}

/* 状态标签样式 */
:deep(.el-tag) {
  font-weight: 500;
}

/* 审批对话框样式 */
.approval-dialog {
  max-height: 70vh;
  overflow-y: auto;
}

.receivable-info {
  margin-bottom: 20px;
}

.amount-text {
  font-weight: bold;
  color: #e6a23c;
}

.approval-form {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.approval-form h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}
</style>
